/*
 * @Author: ylyu
 * @Date: 2024-02-22 13:51:03
 * @LastEditors: ylyu
 * @LastEditTime: 2024-02-23 14:27:08
 * @Description:
 */
import axios from 'axios'
// import { Loading, Message } from 'element-ui'
// import store from '@/stores'
// import { getToken } from '@/utils/auth'
import appConfig from '@/config'

// create axios instance
const instance = axios.create({
  baseURL: appConfig.baseUrl,
  timeout: 600000,
  withCredentials: true, // 表示跨域请求时是否需要使用凭证
})

let reqList = []

axios.defaults.withCredentials = true // 允许跨域携带cookie
// Add a request interceptor
instance.interceptors.request.use(
  (config) => {
    const request = JSON.stringify(config)
    if (!reqList.includes(request)) {
      reqList.push(request)
    }
    // Do something before request is sent
    // startLoading()

    // if (store.getters.token) {
    // let each request carry token
    // ['X-Token'] is a custom headers key
    // please modify it according to the actual situation
    // config.headers['Authorization'] = getToken()
    // }
    return config
  },
  (error) => {
    // Do something with request error

    this.$message.info(error.toString())
    // endLoading()
    return Promise.reject(error)
  }
)

// Add a response interceptor
instance.interceptors.response.use(
  (response) => {
    reqList.splice(
      reqList.findIndex((item) => item === JSON.stringify(response.config)),
      1
    )
    if (reqList.length === 0) {
      // endLoading()
    }

    return response
  },
  (error) => {
    // 发生异常时，请求列表清空
    // 关闭loading
    reqList = []
    // endLoading()
    return Promise.reject(error)
  }
)

export default instance
